package shark.picture.utils.sm4;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * @author: leemon
 * @description: 国密SM4工具类
 * @date: 2024/2/5 11:02
 */
@Slf4j
public class SM4Utils {
    private static final String KEY = "pTcFKXiH7afFQY6r";
    private static final String CBC_IV = "YM637I5ESzj8yeeU";

    public static String encrypt(String msg) {
        String encrypt;
        if (StringUtils.isEmpty(msg)) {
            return null;
        }
        try {
            encrypt = SM4Crypter.encrypt(msg, KEY, CBC_IV);
            encrypt = encrypt.replaceAll("\\+", "@").replaceAll("/", "\\$").replaceAll("=", "*");
        } catch (Exception e) {
            log.info("SM4加密异常", e);
            encrypt = null;
        }
        log.info(StrUtil.format("SM4加密结果  原数据：{}->加密后数据：{}"), msg, encrypt);
        return encrypt;
    }
    public static String encrypt(String msg,String keyStr,String ivStr) {
        String encrypt;
        if (StringUtils.isEmpty(msg)) {
            return null;
        }
        try {
            encrypt = SM4Crypter.encrypt(msg, keyStr, ivStr);
        } catch (Exception e) {
            log.info("SM4加密异常", e);
            encrypt = null;
        }
        log.info(StrUtil.format("SM4加密结果  原数据：{}->加密后数据：{}"), msg, encrypt);
        return encrypt;
    }

    public static String decrypt(String msg) {
        String decrypt;
        try {
            if (StringUtils.isEmpty(msg)) {
                decrypt = null;
            } else {
                msg = msg.replaceAll("@", "+").replaceAll("\\$", "/").replaceAll("\\*", "=");
                decrypt = SM4Crypter.decrypt(msg, KEY, CBC_IV);
            }
        } catch (Exception e) {
            log.info("SM4解密异常", e);
            decrypt = null;
        }
        log.info(StrUtil.format("SM4解密结果  原数据：{}->解密后数据：{}"), msg, decrypt);
        return decrypt;
    }
    public static String decrypt(String msg,String keyStr,String ivStr) {
        String decrypt;
        try {
            if (StringUtils.isEmpty(msg)) {
                decrypt = null;
            } else {
                decrypt = SM4Crypter.decrypt(msg, keyStr, ivStr);
            }
        } catch (Exception e) {
            log.info("SM4解密异常", e);
            decrypt = null;
        }
        log.info(StrUtil.format("SM4解密结果  原数据：{}->解密后数据：{}"), msg, decrypt);
        return decrypt;
    }
}
